﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentScheduler;
using YiYiTong.Rocket.Helper;
using YiYiTong.Rocket.Business;
using YiYiTong.Rocket.Model;
using YiYiTong.Rocket.EFDBFirst;
using YiYiTong.Rocket.Business.Biz;

namespace YiYiTong.Rocket.ProcessConsole
{
    /// <summary>
    /// 竞价
    /// </summary>
    public class JingjiaJob : BaseJob
    {
        static int excutecounts;
        public override void DoAction()
        {
            if (excutecounts % 100 == 0)
            {
                LogHelper.Debug($"竞价执行：{excutecounts}次");
            }
            excutecounts++;

            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            var configlist = dbcontext.ADZ_JingjiaConfig.Where(configT => configT.is_del == 0 && configT.is_show == 1 && configT.jingjia_config_satus == 0 && configT.begin_time <= DateTime.Now).ToList();
            if (configlist.Any())
            {
                configlist.ForEach(configT =>
                {
                    configT.jingjia_config_satus = 1;

                    //将未开始的竞价设置为开始竞价
                    var list = dbcontext.ADZ_JingjiaMaster.Where(t => t.is_del == 0 && t.jingjia_config_id == configT.jingjia_config_id).ToList();
                    if (list.Any())
                    {
                        foreach (var item in list)
                        {
                            var goodslist = dbcontext.ADZ_GoodsJingjia.Where(t => t.jingjia_id == item.jingjia_id).ToList();
                            if (goodslist.Any())
                            {
                                item.jingjia_satus = 1;
                            }
                            else
                            {
                                LogHelper.Error($"竞价时间到了但是竞价的商品未配置：{item.jingjia_name}【{item.jingjia_id}】");
                            }
                        }
                        dbcontext.SaveChanges();
                    }

                    //发送业务消息
                    BusinessMsgBiz.Instance.SendBusinessMsg(new ADZ_BusinessMsg
                    {
                        BusinessMsgType = (int)BusinessMsgEnum.JingjiaBegin,
                        msg = $"竞价 {configT.jingjia_config_name} 已经开始！",
                        msg_title = "竞价开始",
                        msg_url = $""
                    });

                });
            }


            var endconfig = dbcontext.ADZ_JingjiaConfig.Where(t => t.is_del == 0 && t.jingjia_config_satus == 1 && t.end_time <= DateTime.Now).ToList();
            if (endconfig.Any())
            {
                endconfig.ForEach(endt =>
                {
                    endt.jingjia_config_satus = 2;
                    var endmaster = dbcontext.ADZ_JingjiaMaster.Where(master => master.is_del == 0 && master.jingjia_config_id == endt.jingjia_config_id && master.jingjia_satus == 1).ToList();
                    if (endmaster.Any())
                    {
                        endmaster.ForEach(endmasterT =>
                        {
                            if (!endmasterT.real_end_time.HasValue)
                            {
                                endmasterT.real_end_time = endt.end_time;
                            }
                        });
                    }

                    //发送业务消息
                    BusinessMsgBiz.Instance.SendBusinessMsg(new ADZ_BusinessMsg
                    {
                        BusinessMsgType = (int)BusinessMsgEnum.JingjiaEnd,
                        msg = $"竞价 {endt.jingjia_config_name} 已经结束！",
                        msg_title = "竞价结束",
                        msg_url = $""
                    });
                });
            }
            dbcontext.SaveChanges();

            //将到期的竞价设置为竞价结束,并生成待支付订单
            var endlist = dbcontext.ADZ_JingjiaMaster.Where(t => t.is_del == 0 && t.jingjia_satus == 1 && t.real_end_time <= DateTime.Now).ToList();
            if (endlist.Any())
            {
                foreach (var item in endlist)
                {
                    item.jingjia_satus = 2;
                    if (item.liuzhi_price == 0)
                    {
                        if (item.last_price > 0 && item.chujia_counts > 0)
                        {
                            item.jingjia_deal_status = 2;
                        }
                    }
                    if (item.liuzhi_price > 0)
                    {
                        if (item.last_price >= item.liuzhi_price)
                        {
                            item.jingjia_deal_status = 2;
                        }
                    }
                    //剩下的情况均视为流标
                    if (item.jingjia_deal_status == 0)
                    {
                        item.jingjia_deal_status = 1;
                    }

                    dbcontext.SaveChanges();

                    ////成交的才开始下单
                    if (item.jingjia_deal_status == 2)
                    {
                        Tuple<bool, string, string> result = OrderBiz.Instance.CreateJingjiaOrder(item.jingjia_id);
                        if (!result.Item1)
                        {
                            LogHelper.Error($"竞价【{item.jingjia_name}-{item.jingjia_id}】下单失败：{result.Item3}");
                        }
                    }
                    else //设置参与报价无效
                    {
                        var notdelsubmit = dbcontext.ADZ_JingjiaSubmit.Where(t => t.jingjia_id == item.jingjia_id && t.is_del == 0).ToList();
                        if (notdelsubmit.Any())
                        {
                            notdelsubmit.ForEach(t => t.is_del = 1);
                            dbcontext.SaveChanges();
                        }
                    }
                }
            }

            #region 保证金退还
            //竞价已经结束，所有报了名，未退款的
            var baoming_all = (from baoming in dbcontext.ADZ_JingjiaBaomingOrder.Where(t => t.is_succ == 1 && t.order_status == 1 && t.is_apply_refund == 0)
                               join config in dbcontext.ADZ_JingjiaConfig.Where(t => t.jingjia_config_satus == 2 && t.baoming_counts > 0)
                               on baoming.jingjia_config_id equals config.jingjia_config_id
                               select new
                               {
                                   baoming.jingjia_config_id,
                                   baoming.uid,
                                   baoming.seq_id,
                                   baoming.order_amt
                               }).ToList();

            //已中标 未付款的或者订单撤销的不能退
            var submit_all = (from submit in dbcontext.ADZ_JingjiaSubmit.Where(t => t.is_del == 0 && t.is_hit == 1 && (t.status == 2 || t.status == 11))
                              join master in dbcontext.ADZ_JingjiaMaster.Where(t => t.is_del == 0)
                              on submit.jingjia_id equals master.jingjia_id
                              select new
                              {
                                  master.jingjia_config_id,
                                  submit.jingjia_id,
                                  submit.uid
                              }).ToList();

            if (baoming_all.Any())
            {
                if (submit_all.Any())
                {
                    var except_list = (from baoming in baoming_all
                                       join submit in submit_all
                                       on new { baoming.uid, baoming.jingjia_config_id } equals new { submit.uid, submit.jingjia_config_id }
                                       select baoming.seq_id
                                 ).ToList();

                    baoming_all = baoming_all.Except(baoming_all.Where(t => except_list.Contains(t.seq_id))).ToList();
                }
            }

            if (baoming_all.Any())
            {
                baoming_all.ForEach(t =>
                {
                    string str_goods = "";
                    string order_no = Utils.BuildOrderId("T");
                    string apply_user = t.uid.ToString() + " self";
                    var result = OrderBiz.Instance.CreateRefundOrder(order_no, (int)BusinessOrderType.BaomingOrder, t.seq_id, t.order_amt, str_goods, "竞价失败保证金退款", apply_user, "");
                    if (!result.Item1)
                    {
                        LogHelper.Error($"{order_no}保证金退款订单创建失败：{result.Item2}");
                    }
                });
            }

            ////已创建退款，但是未执行的
            var need_refun = dbcontext.ADZ_RefundOrder.Where(t => t.business_order_type == (int)BusinessOrderType.BaomingOrder && t.order_master_id > 0 && t.refund_amt > 0 && t.status == 0).ToList();
            if (need_refun.Any())
            {
                need_refun.ForEach(t =>
                {
                    var result = OrderBiz.Instance.RefundOrder((int)BusinessOrderType.BaomingOrder, t.order_master_id.Value, t.order_no, t.refund_amt.Value);
                    if (!result.Item1)
                    {
                        LogHelper.Error($"{t.order_no}执行退款操作失败：{result.Item2}");
                        t.status = (byte)RefundSatus.Fail;
                    }
                    else
                    {
                        t.status = (byte)RefundSatus.Succ;
                        var baoming1 = dbcontext.ADZ_JingjiaBaomingOrder.FirstOrDefault(baoming => baoming.seq_id == t.order_master_id.Value);
                        baoming1.order_status = 2;

                        //发送业务消息
                        BusinessMsgBiz.Instance.SendBusinessMsg(new ADZ_BusinessMsg
                        {
                            BusinessMsgType = (int)BusinessMsgEnum.JingjiaRefund,
                            msg = $"竞价保证金退款，uid[{baoming1.uid}] ，金额 {t.refund_amt.Value} ！",
                            msg_title = "竞价保证金退款",
                            msg_url = $""
                        });

                        //发送推送消息
                        AddPushMsgModel paramModel = new AddPushMsgModel
                        {
                            aDZ_Pushmessage = new ADZ_Pushmessage
                            {
                                MsgType = 2,
                                ReceiveType = 1,
                                MsgTitle = "竞价报名保证金退款",
                                MsgText = $"您的报名参加的竞价保证金已退款，本次退款金额：￥{t.refund_amt.Value}，请注意查收。"
                            },
                            ReceiveUids = baoming1.uid.ToString()
                        };
                        PushMsgBiz.Instance.AddPushMsg(paramModel);
                    }
                });
            }
            dbcontext.SaveChanges();
            #endregion
        }
    }
}
